package cn.starrysky.hrm.userdetails;

import cn.starrysky.hrm.client.SystemClient;
import cn.starrysky.hrm.domain.LoginUser;
import cn.starrysky.hrm.domain.Permission;
import cn.starrysky.hrm.exception.GlobalException;
import cn.starrysky.hrm.mapper.LoginUserMapper;
import cn.starrysky.hrm.mapper.PermissionMapper;
import cn.starrysky.hrm.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private LoginUserMapper loginUserMapper;

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private SystemClient systemClient;

    /**
     * 加载数据库中的认证的用户的信息：用户名，密码，用户的权限列表
     * @param username: 该方法把username传入进来，
        我们通过username查询用户的信息(密码，权限列表等)
        然后封装成 UserDetails进行返回 ，交给security 。
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //User是security内部的对象，UserDetails的实现类 ，
        //用来封装用户的基本信息（用户名，密码，权限列表）
        //public User(String username, String password, Collection<? extends GrantedAuthority> authorities)

        
        LoginUser userFromDB = loginUserMapper.selectByUsername(username);
        if(null == userFromDB){
            throw new RuntimeException("无效的用户");
        }

        //模拟存储在数据库的用户的密码：123
        //String password = passwordEncoder.encode("123");
        String password = userFromDB.getPassword();

        //查询用户的权限
        List<Permission> permission = permissionMapper.selectPermissionsByUserId(userFromDB.getId());

        //用户的权限列表,暂时为空
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        permission.forEach(e->{
            System.out.println("用户："+userFromDB.getUsername()+" 加载权限："+e.getSn());
            authorities.add(new SimpleGrantedAuthority(e.getSn()));
        });

        String resultjson=username;
        //后台管理用户需要机构信息
        if(userFromDB.getType()==LoginUser.TYPE_ADMIN){
            //获取上下文usercontext
            AjaxResult userContext = systemClient.getUserContext(userFromDB.getId());
            if(!userContext.isSuccess()){
                throw new GlobalException("系统链接失败");
            }
            //获取json
            resultjson = userContext.getResultObj().toString();
        }

        User user = new User(resultjson, password, authorities);

        return user;
    }
}